//
//  AppDelegate.m
//  XiaoMiao
//
//  Created by 23 on 2017/11/4.
//  Copyright © 2017年 smallyou. All rights reserved.
//

#import "AppDelegate.h"
#import "XMNavigationController.h"
#import "XMHomeController.h"
#import "AppDelegate+Common.h"
#import "KLNewFeatureConfig.h"

#import "LoginController.h"
#import "PerfectInfoController.h"
#import "ConsumerCreatController.h"

#import <Bugly/Bugly.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>


#define kDeviceVersion  [[UIDevice currentDevice] systemVersion].floatValue

@interface AppDelegate ()<JPUSHRegisterDelegate>

//网络监控
@property(nonatomic,strong)YYReachability* reachability;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    

    
    //设置App窗口
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.backgroundColor = [UIColor whiteColor];
    self.window = window;
    [window makeKeyAndVisible];
    XMHomeController *homeVc = [[XMHomeController alloc] init];
//    ConsumerCreatController *homeVc = [[ConsumerCreatController alloc] init];
    XMNavigationController *nav = [[XMNavigationController alloc] initWithRootViewController:homeVc];
    window.rootViewController = nav;
    
    //公共配置相关
    [self setupCommonWithApplication:application didFinishLaunchingWithOptions:launchOptions];
    

    
    [KLNewFeatureConfig configWithComplete:^{
        //
    }];

    //配置bugly
    [Bugly startWithAppId:@"4699b8bb93"];
    
    
    //创建网络监控
    self.reachability = [YYReachability reachability];
    @weakify(self);
    self.reachability.notifyBlock = ^(YYReachability *reachability){
        [weak_self networkChanged:reachability];
    };
    
    
    //极光推送
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
//    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"8a928ac087f8f6883ec40f2c"
                          channel:@"App Store"
                 apsForProduction:0
            advertisingIdentifier:nil];
    
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    
    
    
    /**
     *  iOS8以后需要注册,才能将未读的数在图标右上角显示
     */
    if (kDeviceVersion >= 8.0) {
        // 使用本地通知 (本例中只是badge，但是还有alert和sound都属于通知类型,其实如果只进行未读数在appIcon显示,只需要badge就可, 这里全写上为了方便以后的使用)
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        // 进行注册
        [application registerUserNotificationSettings:settings];
    }
    
    return YES;
}

#pragma mark --- 网络判断 ---

-(void)networkChanged:(YYReachability*)reachability{
    YYReachabilityStatus status = reachability.status;
    switch (status) {
        case YYReachabilityStatusNone:
        {
            
            NSLog(@"网络服务已断开");
        }
            break;
        case YYReachabilityStatusWiFi:
        {
            NSLog(@"WIFI网络");
            
        }
            break;
        case YYReachabilityStatusWWAN:
        {
            NSLog(@"移动网络");
            YYReachabilityWWANStatus wwStatus = reachability.wwanStatus;
            switch (wwStatus) {
                case YYReachabilityWWANStatus2G:
                    NSLog(@"2G网络");
                    
                    break;
                case YYReachabilityWWANStatus3G:
                    NSLog(@"3G网络");
                    
                    break;
                case YYReachabilityWWANStatus4G:
                    NSLog(@"4G网络");
                    
                    break;
                case YYReachabilityWWANStatusNone:
                    
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
}



#pragma mark ----jpushDelegate
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [AppGlobal updateDeviceToken:[deviceToken md5String]];
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    //现在只有退出登录有推送 先不根据参数做处理
    [AppNotificationHelpper postNotificationName:kLoginSessionTimeoutNotification object:nil];

}




@end
